package com.erpanderp.wam.usm.view.user;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import org.primefaces.context.RequestContext;

import com.erpanderp.wam.usm.model.entity.complaintandsuggestion.ComplaintAndSuggestion;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.user.ComplaintsAndSuggestionDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeAndReportingDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;

@ViewScoped
@ManagedBean
public class ComplaintsAndSuggestionsBean implements Serializable {
	
	private static final long serialVersionUID = 1L;
	private HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	private ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	private WAMUser wamUser = (WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
	private TimeZone timeZone = TimeZone.getDefault();
	
	private List<ComplaintAndSuggestion> complaintAndSuggestions = new ArrayList<ComplaintAndSuggestion>();
	
	ComplaintsAndSuggestionDAO complaintsAndSuggestionDAO = new ComplaintsAndSuggestionDAO();
	
	private ComplaintAndSuggestion complaintAndSuggestion =new ComplaintAndSuggestion();
	
	private boolean FORM_VALID;
	private String EMAIL_MESSAGE;
	private EmailUtil emailUtil;

	public ComplaintsAndSuggestionsBean(){
		
		complaintAndSuggestions = complaintsAndSuggestionDAO.getAllCompliantsAndSuggestions();
		for(ComplaintAndSuggestion complaintAndSuggestion : complaintAndSuggestions){
			complaintAndSuggestion.setBriefComplaint(complaintAndSuggestion.getComplaint()!= null && complaintAndSuggestion.getComplaint().length() > 50 ? complaintAndSuggestion.getComplaint().substring(0, 50) + "..." : complaintAndSuggestion.getComplaint() + "...");
			
			if(complaintAndSuggestion.getReply()!= null){
				complaintAndSuggestion.setBriefReply(complaintAndSuggestion.getReply()!= null && complaintAndSuggestion.getReply().length() > 40 ? complaintAndSuggestion.getReply().substring(0, 40) + "..." : complaintAndSuggestion.getReply() + "...");
			}else{
				complaintAndSuggestion.setBriefReply("No Reply");
			}
				
		}
		
	}
	
	
	public void replyToComplaintListener(ActionEvent e)  {
		 
		 Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		  
		String complaintCode = params.get("complaintCode");

		complaintAndSuggestion=complaintsAndSuggestionDAO.getComplaintAndSuggestionByCode(complaintCode);
		
   }
	
	 public String saveReplyAction()  {
			
		 validateForm();
		   if(FORM_VALID){
		
			   complaintAndSuggestion.setDateModified(new Date());
			   complaintAndSuggestion.setModifiedBy(wamUser.getEmployee().getFirstName()+" "+wamUser.getEmployee().getLastName());
			  
			   complaintsAndSuggestionDAO.createComplaintAndSuggestion(complaintAndSuggestion);
			   
			   System.out.println("AT CALLER METHOD: " + sendMessage());  //*******DONT REMOVE*******
			   
			   return "complaintsandsuggestions";
		    }else{		    	
		    	RequestContext.getCurrentInstance().execute("replyCSDialog.show();");
		    	return null;
		    }
		 }
	 
	// COMPLAINT INPUTS VALIDATIONS
	private void validateForm() {
		FORM_VALID = true;

			if (ValidationUtil.isEmpty(complaintAndSuggestion.getReply(), "Reply ", null,
					FacesContext.getCurrentInstance()) != null) {
				FORM_VALID = false;
			}
	}
	
	//SENDING EMAIL 
			public String sendMessage(){
				Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
				String domainName = context.getInitParameter("domainName");
				String messageString ="";
				
				
				String employeeMail =null;
				
				
				emailUtil = new EmailUtil();
				if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
					System.out.println("PRODUCTION");
					employeeMail = complaintAndSuggestion.getEmployee().getEmail();
					
				} else {
					System.out.println("DEVELOPMENT");
					employeeMail = hostsMap.get(CommonLookup.DEV_EMAIL);	
				}	
				
				String[] to={employeeMail};
				
				messageString = "Dear " + complaintAndSuggestion.getEmployee().getFirstName() + " " + complaintAndSuggestion.getEmployee().getLastName() + "" +
									",<br/><br/>" +									
							
				        
						"<b>Your Complaint/Suggestion : </b><br/>"+complaintAndSuggestion.getComplaint()+"<br/><br/>"+
				        "<b> Reply : </b><br/>"+complaintAndSuggestion.getReply()+"<br/><br/>"+
				       
						"<font size='1.5' face='verdana' color='red'><br><br><b><u>NOTE :</u> <br><br>" +

	                    "1. Don't Reply to this Mail.<br>" +
	                    "2. If you have any queries/more details please email to : hr@erpanderp.com .</b> </font> <br><br><br>" +
						
						"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;
					
					emailUtil = new EmailUtil();
					emailUtil.setMessage(messageString);
					emailUtil.setRecieverAddresses(to);
					
					emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
					
					emailUtil.setSubject("WAM  Complaint/Suggestion (" + complaintAndSuggestion.getCode() + ")");
					
				
					
				
				
				SwingWorker worker = new SwingWorker<String, Object>() {
					@Override
					protected String doInBackground() throws Exception {
						EMAIL_MESSAGE = emailUtil.processAndSendEmail();
						return null;
					}

					@Override
					protected void done() {
							System.out.println("DONE " + EMAIL_MESSAGE);		
					}
				};
				worker.execute();
				System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
				return EMAIL_MESSAGE;
			}
	
	//GENERATE SETTERS AND GETTERS
	public List<ComplaintAndSuggestion> getComplaintAndSuggestions() {
		return complaintAndSuggestions;
	}

	public void setComplaintAndSuggestions(List<ComplaintAndSuggestion> complaintAndSuggestion) {
		this.complaintAndSuggestions = complaintAndSuggestion;
	}


	public ComplaintAndSuggestion getComplaintAndSuggestion() {
		return complaintAndSuggestion;
	}


	public void setComplaintAndSuggestion(ComplaintAndSuggestion complaintAndSuggestion) {
		this.complaintAndSuggestion = complaintAndSuggestion;
	}


	public boolean isFORM_VALID() {
		return FORM_VALID;
	}


	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}


	public WAMUser getWamUser() {
		return wamUser;
	}


	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}


	public TimeZone getTimeZone() {
		return timeZone;
	}


	public void setTimeZone(TimeZone timeZone) {
		this.timeZone = timeZone;
	}

}
